package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustException;
import com.heima.common.exception.CustomException;
import com.heima.file.service.impl.OSSAliyunFileStorageService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmMaterialDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.threadlocal.WmThreadLocalUtils;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Currency;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {

    @Autowired
    private OSSAliyunFileStorageService ossService;

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    @Value("${file.oss.profix}")
    String profix;

    @Value("${file.oss.endpoint}")
    String endpoint;

    @Value("${file.oss.web-site}")
    String webSite;

    /**
     * 图片上传
     *
     * @param multipartFile
     * @return
     */
    @Override
    public ResponseResult uploadPhoto(MultipartFile multipartFile) {
        // 参数校验
        if (multipartFile.isEmpty()) {
            return ResponseResult.errorResult(AppHttpCodeEnum.FILE_UPLOAD_PARAMREQUIRE_ERROR);
        }
        // 判断thread local是否有user
        WmUser wmUser = WmThreadLocalUtils.getUser();
        if (wmUser == null || wmUser.getId() == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        // 上传
        String store = null;
        try {
            String fileName = UUID.randomUUID().toString().replace("-", "") +
                    multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf("."));
            store = ossService.store(profix, fileName, multipartFile.getInputStream());
        } catch (IOException e) {
            log.error("WmMaterialServiceImpl uploadPicture error: {}", e);
            e.printStackTrace();
            throw new CustomException(AppHttpCodeEnum.FILE_UPLOAD_ERROR);
        }
        // 保存到数据库
        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setUserId(wmUser.getId());
        wmMaterial.setIsCollection((short) 0);
        wmMaterial.setType((short) 0);
        wmMaterial.setCreatedTime(new Date());
        wmMaterial.setUrl(store);
        this.save(wmMaterial);
        // 返回给前端
        wmMaterial.setUrl(webSite + store);
        return ResponseResult.okResult(wmMaterial);
    }

    /**
     * 素材列表分页
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findPage(WmMaterialDto dto) {
        // 判断参数
        if (dto == null || dto.getIsCollection() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        WmUser wmUser = WmThreadLocalUtils.getUser();
        if (wmUser == null || wmUser.getId() == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        dto.checkParam();
        // 根据是否收藏和用户id分页查询
        LambdaQueryWrapper<WmMaterial> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(WmMaterial::getUserId, wmUser.getId());
        if (dto.getIsCollection() == 1) {
            wrapper.eq(WmMaterial::getIsCollection, dto.getIsCollection());
        }

        // 时间倒序
        wrapper.orderByDesc(WmMaterial::getCreatedTime);
        IPage<WmMaterial> iPage = this.page(new Page<WmMaterial>(dto.getPage(), dto.getSize()), wrapper);

        // 设置图片全路径
        List<WmMaterial> wmMaterialList = iPage.getRecords();
        wmMaterialList.stream().forEach(wmMaterial -> {
            wmMaterial.setUrl(webSite + wmMaterial.getUrl());
        });
        // 返回结果
        return new PageResponseResult(dto.getPage(), dto.getSize(), (int) iPage.getTotal(), wmMaterialList);
    }

    /**
     * 删除图片
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult deletePhoto(Integer id) {
        // 校验参数
        if (id == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        if (WmThreadLocalUtils.getUser() == null || WmThreadLocalUtils.getUser().getId() == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        if (this.getById(id) == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        // 判断WmNewsMateria中是否引用该图片
        Integer count = wmNewsMaterialMapper.selectCount(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getMaterialId, id));
        if (count > 0) {
            CustException.cust(AppHttpCodeEnum.FILE_DELETE_ERROR);
        }

        // 删除图片 OSS  数据库
        ossService.delete(this.getById(id).getUrl());
        this.removeById(id);
        // 返回参数
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 收藏/取消
     *
     * @param id
     * @param collectMaterial
     * @return
     */
    @Override
    public ResponseResult updateCollectionStatus(Integer id, Short collectMaterial) {
        // 参数校验
        if (id == null || collectMaterial == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        if (WmThreadLocalUtils.getUser() == null || WmThreadLocalUtils.getUser().getId() == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        WmMaterial wmMaterial = this.getById(id);
        if (wmMaterial == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        // 根据id更新
        wmMaterial.setIsCollection(collectMaterial);
        this.updateById(wmMaterial);
        // 返回结果
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
